package com.yl.common

import com.baomidou.mybatisplus.annotation.EnumValue
import com.fasterxml.jackson.annotation.JsonValue
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap

/**
 *
 * create by 2021/5/11.
 * @author udbjqr
 */
data class WebContext(
    var userType: UserType = UserType.Unknown,
    var companyId: Long = 0,
    var userId: Long = 0,
    var subCompanyId:Long = 0
)


enum class UserType(@EnumValue val value: Int, @JsonValue val show:String) {
	Unknown(99,"Unknown"),
	Admin(1,"Admin"),
	Company(2,"Company"),
	Custom(3,"Custom");

	companion object {
		fun getEnum(d: Int?): UserType {
			return UserType.values().find { it.value == (d ?: return UserType.Unknown) } ?: UserType.Unknown
		}
	}
}


private val contexts: ConcurrentMap<Long, WebContext> by lazy {
	ConcurrentHashMap()
}


fun setContext(context: WebContext) {
	contexts[Thread.currentThread().id] = context
}


fun getContext(): WebContext {
	val id = Thread.currentThread().id
	if (!contexts.containsKey(id)) {
		contexts[id] = WebContext()
	}

	return contexts[id]!!
}

fun clearContext() {
	contexts.remove(Thread.currentThread().id)
}
